package com.wly.jmockito.proxyutil;

import com.wly.jmockito.service.UserService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * Description: 代理工具类，为了代理userservice业务方法执行每次都要记录方法执行时间
 * Copyright: Copyright (c) 2024
 * Create Time: 2024-11-08 17:02
 *
 * @author wanglianyun
 */
public class ProxyUtil {

    public static UserService createProxy(UserService userService) {
        UserService userServiceProxy = (UserService)Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),
                new Class[]{UserService.class}, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("login") || method.getName().equals("deleteUsers")) {
                    long start = System.currentTimeMillis();
                    // 执行方法
                    Object response = method.invoke(userService, args);
                    long end = System.currentTimeMillis();
                    System.out.println("用户" + method.getName() + "方法执行时间为：" + (end - start) / 1000 + "s");
                    return response;
                } else {
                    Object response = method.invoke(userService, args);
                    return response;
                }
            }
        });

        return userServiceProxy;
    }
}
